import java.util.Arrays;
import java.util.Stack;

public class Sort {
    public static void quickSort(int[]array){
        int left=0;
        int right=array.length-1;
        int pivot=partition(array,left,right);
        Stack<Integer>stack=new Stack<>();
        if(pivot>left+1){
            stack.push(left);
            stack.push(pivot-1);
        }
        if(pivot<right-1){
            stack.push(pivot+1);
            stack.push(right);
        }
        while(!stack.isEmpty()){
            right=stack.pop();
            left=stack.pop();
            pivot=partition(array,left,right);
            if(pivot>left+1){
                stack.push(left);
                stack.push(pivot-1);
            }
            if(pivot<right-1){
                stack.push(pivot+1);
                stack.push(right);
            }
        }
    }
/*    int count=0;
    public int size(Node root){
        if(root==null){
            return 0;
        }
        count++;
        size(root.left);
        size(root.right);
    }
    public int size(Node root){
        if(root==null){
            return 0;
        }
        return size(root.left)+size(root.right)+1;
    }*/

    public static int partition(int []array,int start,int end){
        int tmp=array[start];
        while(start<end){
            while(start<end&&array[end]>=tmp){
                end--;
            }
            array[start]=array[end];
            while (start<end&&array[start]<=tmp){
                start++;
            }
            array[end]=array[start];
        }
        array[start]=tmp;
        return start;
    }


    public static void main(String[]args){
        int[]array={55,66,44,33,22,11,2,9,43};
        quickSort(array);
        System.out.println(Arrays.toString(array));
    }

}
